package com.quartz.service;

import com.quartz.example.CronTriggerOne;
import com.quartz.job.GirlOne;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

import static org.quartz.CronScheduleBuilder.cronSchedule;

@Component
public class QuartzOneService  {
    private Scheduler scheduler;

    public QuartzOneService() throws Exception{
        this.scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail jobDetail = this.getJob();
        Trigger trigger = this.cron(jobDetail,"0/1 * * * * ?");
        this.scheduler.scheduleJob(jobDetail,trigger);
    }


    public Trigger cron(JobDetail jobDetail, String cron){
        //使用 cron表达式
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(UUID.randomUUID().toString())
                .forJob(jobDetail)
                .withSchedule(cronSchedule(cron))
                .build();
        return trigger;
    }
    public JobDetail getJob(){
        JobDetail jobDetail = JobBuilder.newJob(GirlOne.class).build();
        return jobDetail;
    }

    public Boolean stop() throws Exception{
        scheduler.shutdown();
      return scheduler.isShutdown();
    }
    public Boolean start() throws Exception{
       scheduler.start();
      return scheduler.isStarted();
    }
    public Boolean changeCron(String cron) throws Exception{
        this.stop();
        this.scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail jobDetail  = this.getJob();
      Trigger  trigger = this.cron(jobDetail,cron);
        scheduler.scheduleJob(jobDetail,trigger);
      return this.start();
    }

}
